package com.ranqianhui.randyojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ranqianhui.randyojcodesandbox.model.ExecuteCodeRequest;
import com.ranqianhui.randyojcodesandbox.model.ExecuteCodeResponse;
import com.ranqianhui.randyojcodesandbox.model.ExecuteMessage;
import com.ranqianhui.randyojcodesandbox.model.JudgeInfo;
import com.ranqianhui.randyojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox{
        private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
        private static final String GLOBAL_CODE_CLASS_NAME = "Main.java";
        public static final long TIME_OUT=5000L;
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String languge = executeCodeRequest.getLanguage();
        //1.保存代码为文件
        File userCodeFile= saveCodeFile(code);
        //2.编译代码，得到class文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(compileFileExecuteMessage);
        //3.执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);
        //4.收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessageList);
        //5.文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b){
            log.error("deleteFile error, userCodeFilePath={}",userCodeFile.getAbsolutePath());
        }
        return executeCodeResponse;
    }
    /***
     * 1.把用户代码保存为文件
     * @param code 用户代码
     * @return
     */
      public File saveCodeFile(String code){
            String userDir = System.getProperty("user.dir");
            String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
            //判断全局代码目录是否存在
            if (!FileUtil.exist(globalCodePathName)) {
                FileUtil.mkdir(globalCodePathName);
            }
            //把用户的代码隔离存储
            String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
            String userCodePath = userCodeParentPath + File.separator + GLOBAL_CODE_CLASS_NAME;
            File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
            return userCodeFile;
         }

    /**
     * 2.编译代码
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile){
             String compileCmd = String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
             try {
                 Process compileProcess = Runtime.getRuntime().exec(compileCmd);
                 ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
                 if (executeMessage.getExitValue()!=0){
                     throw new RuntimeException("编译错误");
                 }
                 return executeMessage;
             } catch (Exception ioException) {
                 throw new RuntimeException(ioException);
             }
         }

    /**
     * 3.执行代码,获取执行结果列表
     * @param compileFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File compileFile,List<String> inputList){
             String userCodeParentPath =compileFile.getParentFile().getAbsolutePath();
             List<ExecuteMessage> executeMessageList = new ArrayList<>();
             for (String inputArgs : inputList) {
                 String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s  Main %s", userCodeParentPath,inputArgs);
                 try {
                     Process runProcess = Runtime.getRuntime().exec(runCmd);
                     //超时控制
                     new Thread(()->{
                         try {
                             Thread.sleep(TIME_OUT);
                             runProcess.destroy();
                         } catch (InterruptedException e) {
                             throw new RuntimeException(e);
                         }
                     }).start();
                     ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runProcess, "运行", inputArgs);
                     executeMessageList.add(executeMessage);
                 } catch (Exception e) {
                     throw new RuntimeException("代码执行错误"+e);
                 }
             }
             return executeMessageList;
         }

    /**
     * 4.获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList){
             ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
             List<String> outputList = new ArrayList<>();
             //取用时最大值，判断是否超时
             Long maxTime = 0L;
             for (ExecuteMessage executeMessage : executeMessageList) {
                 String errorMessage = executeMessage.getErrorMessage();
                 if (StrUtil.isNotBlank(errorMessage)) {
                     executeCodeResponse.setMesssge(errorMessage);
                     // 执行中存在错误
                     executeCodeResponse.setStatus(3);
                     break;
                 }
                 outputList.add(executeMessage.getMessage());
                 if (executeMessage.getTime() != null) {
                     maxTime = Math.max(maxTime, executeMessage.getTime());
                 }
             }
             if (outputList.size() == executeMessageList.size()) {
                 executeCodeResponse.setStatus(1);
             }
             executeCodeResponse.setOutputList(outputList);
             JudgeInfo judgeInfo = new JudgeInfo();

             judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();
             executeCodeResponse.setJudgeInfo(judgeInfo);
             return executeCodeResponse;
         }

    /**
     * 5.删除文件
     * @param userCodeFile
     * @return
     */
        public boolean deleteFile(File userCodeFile){
            if (userCodeFile.getParentFile() != null) {
                boolean del = FileUtil.del(userCodeFile.getParentFile().getAbsoluteFile());
                System.out.println("删除" + (del ? "成功" : "失败"));
                return del;
            }
            return true;
        }

    /**
     * 6.获取错误响应
     * @param a
     * @return
     */
        private ExecuteCodeResponse getErrorResponse(Throwable a) {
            ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
            executeCodeResponse.setOutputList(new ArrayList<>());
            executeCodeResponse.setMesssge(a.getMessage());
            executeCodeResponse.setStatus(2);
            executeCodeResponse.setJudgeInfo(new JudgeInfo());
            return executeCodeResponse;
        }
    }
